#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
工具函数模块
"""

import os
import sys
import time
from datetime import datetime

def check_dependencies():
    """检查依赖包"""
    try:
        import pkg_resources
        required_packages = ['PyQt5', 'opencv-python', 'mss', 'numpy']
        installed_packages = {pkg.key for pkg in pkg_resources.working_set}
        missing_packages = [pkg for pkg in required_packages if pkg.lower() not in installed_packages]
        
        if missing_packages:
            print(f"缺少以下依赖包: {', '.join(missing_packages)}")
            print("请使用以下命令安装依赖:")
            print(f"pip install -i https://pypi.tuna.tsinghua.edu.cn/simple {' '.join(missing_packages)}")
            sys.exit(1)
    except ImportError:
        pass  # 如果pkg_resources不可用，跳过检查

def resource_path(relative_path):
    """获取资源文件的绝对路径"""
    try:
        # PyInstaller创建临时文件夹并将路径存储在_MEIPASS中
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    
    return os.path.join(base_path, relative_path)

def format_time(seconds):
    """将秒数格式化为时:分:秒格式"""
    hours = seconds // 3600
    minutes = (seconds % 3600) // 60
    secs = seconds % 60
    return f"{hours:02d}:{minutes:02d}:{secs:02d}"

def generate_output_filename():
    """生成默认输出文件名"""
    return datetime.now().strftime("录屏_%Y%m%d_%H%M%S.mp4")

def get_desktop_path():
    """获取桌面路径"""
    return os.path.join(os.path.expanduser("~"), "Desktop")

def ensure_directory_exists(directory):
    """确保目录存在，如果不存在则创建"""
    if not os.path.exists(directory):
        os.makedirs(directory)
    return directory

def get_default_save_directory():
    """获取默认保存目录"""
    save_dir = os.path.join(get_desktop_path(), "录屏文件")
    return ensure_directory_exists(save_dir)

def get_file_size_str(file_path):
    """获取文件大小的字符串表示"""
    if not os.path.exists(file_path):
        return "0 KB"
    
    size_bytes = os.path.getsize(file_path)
    if size_bytes < 1024:
        return f"{size_bytes} B"
    elif size_bytes < 1024 * 1024:
        return f"{size_bytes / 1024:.1f} KB"
    elif size_bytes < 1024 * 1024 * 1024:
        return f"{size_bytes / (1024 * 1024):.1f} MB"
    else:
        return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"